package com.example.demo.common.util;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.symmetric.SM4;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import java.security.Security;

/**
* @Description 国密加密解密，用于数据库的加解密
* @Author LLZ
* @Date
*/

public final class SM4Encryptor {


  private static final String KEY = "1Jy22_geneplus@!";

  /**
   *          <dependency>
   *             <groupId>org.bouncycastle</groupId>
   *             <artifactId>bcprov-jdk15to18</artifactId>
   *             <version>1.72</version>
   *         </dependency>
   */
  static{
    Security.addProvider(new BouncyCastleProvider());
  }


  /**
   * 加密字符串,单独提取出来供其他地方使用
   * @param plaintext 文本
   * @return
   */
  public static String encryptStr(String plaintext) {
    if (StrUtil.isBlank(plaintext)) {
      return plaintext;
    }
    SM4 sm4 = new SM4(Mode.ECB, Padding.PKCS5Padding, KEY.getBytes());
    return sm4.encryptHex(String.valueOf(plaintext));
  }

  /**
   * 解密字符串,单独提取出来供其他地方使用
   * @param ciphertext 文本
   * @return
   */
  public static String decryptStr(String ciphertext) {
    if (StrUtil.isBlank(ciphertext)) {
      return ciphertext;
    }
    try {
      SM4 sm4 = new SM4(Mode.ECB, Padding.PKCS5Padding, KEY.getBytes());
      return sm4.decryptStr(String.valueOf(ciphertext));
    } catch (Exception e) {
      throw new RuntimeException("【" + ciphertext + "】解密失败，请检查数据，原因：" + e.getMessage());
    }
  }



  public static void main(String[] args) {
    String encryptStr = encryptStr("1234");
    System.out.println("加密结果：" + encryptStr);
    System.out.println("解密结果：" + decryptStr(encryptStr));
  }
}
